<template>
  <el-dialog v-model="dialogVisible" title="分配角色" width="50%" :before-close="closeRoleDialog">
    <div class="dialog_showRoleDialog">
      <el-scrollbar>
        <!-- 使用穿梭框 来处理数据 -->
        <div style="text-align: center">
          <el-transfer
            v-model="rightValue"
            :props="{ key: 'id', label: 'roleName' }"
            style="text-align: left; display: inline-block"
            filterable
            :titles="['未有角色', '已有角色']"
            :button-texts="['移除', '添加']"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}',
            }"
            :data="tableData"
            @change="handleChange"
          >
            <template #default="{ option }">
              <div class="roleDialog_transfer">
                <div>{{ option.roleName }}</div>
                <div>
                  <el-tag type="success" size="small" v-if="option.isActive">启用</el-tag>
                  <el-tag type="danger" size="small" v-else>停用</el-tag>
                </div>
              </div>
            </template>
          </el-transfer>
        </div>
      </el-scrollbar>
    </div>
    <template #footer>
      <el-button type="success" size="default" @click="submitUserRoles">保存</el-button>
      <el-button type="default" size="default" @click="closeRoleDialog">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, reactive, getCurrentInstance } from "vue";
import { allotUserRole } from "network/user.js";
const { proxy } = getCurrentInstance();

let props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  userInfo: {
    type: Object,
    default() {
      return {};
    },
  },
  roleList: {
    type: Array,
    default() {
      return [];
    },
  },
});
let emits = defineEmits(["closeRoleDialog"]);
let dialogVisible = ref(false);
let tableData = ref([]);
let userInfo = ref({});
let rightValue = ref(null);
watch(
  () => props.visible,
  (newValue, oldValue) => {
    dialogVisible.value = newValue;
    tableData.value = props.roleList;
    userInfo.value = props.userInfo;
    rightValue.value = props.roleList.filter((p) => p.isUserRole == true).map((p) => p.id);
  },
  { immediate: true }
);
const closeRoleDialog = () => {
  emits("closeRoleDialog");
};
//提交变化绑定的角色
const submitUserRoles = async () => {
  const userId = userInfo.value.id;
  const res = await allotUserRole(userId, rightValue.value);
  if (!res.success) return proxy.$notify.error({ message: res.msg, showClose: true });
  proxy.$notify.success({ message: res.msg, showClose: true });
  closeRoleDialog();
};
//穿梭框数据变化时触发,rightValue中存储右侧的id,rightValue为响应式的,因此不需要特殊处理
const handleChange = (value, direction, movedKeys) => {};
</script>

<style lang="less" scoped>
.dialog_showRoleDialog {
  height: 50vh;
}
.roleDialog_transfer {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}
</style>
